package net.lwf.hibernate.dao;

import java.util.Date;
import java.util.List;


import net.lwf.exception.ExceptionUtil;
import net.lwf.hibernate.entity.AppHitLog;
import net.lwf.hibernate.util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class AppHitDAO extends BaseDAO {

	@SuppressWarnings("unchecked")
	public long getHitCounter() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String SQL_QUERY = "select max(hits) from AppHitLog apphitlog";
		long counter = 0;
		try {
			Query query = session.createQuery(SQL_QUERY);
			List<Object> list = query.list();
			Long obj = (Long) list.get(0);
			
			if(obj != null) {
				counter = obj.longValue();
			}		
		}
	    catch(HibernateException hex) {
	    	ExceptionUtil.logAndThrowException(AppHitDAO.class, hex);
	    }
	    finally {
	    	if(session != null) {
	    		session.close();
	    	}
	    }

		return counter;
	}
	
	public void logHit(long counter) {
		AppHitLog log = new AppHitLog();
		log.setHits(counter);
		log.setUpdatedOn(new Date());
		Transaction tx = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			session.save(log);
			tx.commit();
		} 
	    catch(HibernateException hex) {
	    	rollback(tx);
	    	ExceptionUtil.logAndThrowException(AppHitDAO.class, hex);
	    }
	    finally {
	    	if(session != null) {
	    		session.close();
	    	}
	    }
	}


}
